package api

import (
	"context"
	"doctor_srv/global"
	"doctor_srv/model"
	"doctor_srv/model/dao"
	pb "doctor_srv/proto"
)

func (d *DoctorServer) PatientList(ctx context.Context, req *pb.PatientListRequest) (resp *pb.PatientListResponse, err error) {

	var patient []model.Patient
	if req.Status != 0 {
		patient, err = dao.GetPatientByDoctorID(req.DoctorId, req.Status)
		if err != nil {
			return nil, err
		}
	} else {
		patient, err = dao.GetPatientByDoctorID1(req.DoctorId)
		if err != nil {
			return nil, err
		}
	}
	var result []*pb.Patients
	for _, v := range patient {
		result = append(result, &pb.Patients{
			PatientId: int32(v.ID),
			DoctorId:  int32(v.DoctorID),
			Name:      v.Name,
			Age:       int32(v.Age),
			Sex:       int32(v.Sex),
			Status:    int32(v.Status),
		})
	}
	return &pb.PatientListResponse{Items: result}, nil

}

func (d *DoctorServer) PatientShow(ctx context.Context, req *pb.PatientShowRequest) (resp *pb.PatientShowResponse, err error) {

	info := dao.GetPatientInfo(req.PatientId)

	var result []*pb.PatientInfo
	var data []*pb.Folders
	for _, patient := range info {

		for _, folder := range patient.Folder {
			data = append(data, &pb.Folders{
				FolderId: int32(folder.ID),
				Name:     folder.Name,
			})
		}
		result = append(result, &pb.PatientInfo{
			PatientId: int32(patient.ID),
			DoctorId:  int32(patient.DoctorID),
			Name:      patient.Name,
			Age:       int32(patient.Age),
			Sex:       int32(patient.Sex),
			Status:    int32(patient.Status),
			Items:     data,
		})

	}
	return &pb.PatientShowResponse{PatientInfo: result}, nil
}

func (d *DoctorServer) PatientData(ctx context.Context, req *pb.PatientDataRequest) (resp *pb.PatientDataResponse, err error) {
	var Patient []model.Patient
	global.DB.Where("id = ?", req.PatientId).Preload("Folder").Find(&Patient)

	var result []*pb.PatientInfos
	var data []*pb.Folder
	for _, patient := range Patient {

		for _, folder := range patient.Folder {
			var count int64
			global.DB.Model(&model.Record{}).Where("folder_id = ?", folder.ID).Count(&count)
			data = append(data, &pb.Folder{
				Count: int32(count),
				Name:  folder.Name,
			})
		}
		result = append(result, &pb.PatientInfos{
			PatientId: int32(patient.ID),
			DoctorId:  int32(patient.DoctorID),
			Name:      patient.Name,
			Age:       int32(patient.Age),
			Sex:       int32(patient.Sex),
			Status:    int32(patient.Status),
			Items:     data,
		})
	}
	return &pb.PatientDataResponse{PatientInfo: result}, nil
}

func (d *DoctorServer) Add(ctx context.Context, req *pb.AddRequest) (resp *pb.AddResponse, err error) {

	Folder := model.Folder{
		Name: req.Name,
	}
	if err = global.DB.Create(&Folder).Error; err != nil {
		return nil, err
	}
	return &pb.AddResponse{Success: true}, nil
}
